package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.service.cargo.PackingService;
import cn.itcast.vo.ExportProductVo;
import cn.itcast.vo.ExportResult;
import cn.itcast.vo.ExportVo;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.zookeeper.data.Id;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/export")
@Slf4j
public class ExportController extends BaseController {

    @Reference(retries = 0)
    private ContractService contractService;
    @Reference(retries = 0)
    private ExportService exportService;
    @Reference(retries = 0)
    private ExportProductService exportProductService;
    @Reference(retries = 0)
    private PackingService packingService;

    /**
     * 1. 合同管理列表
     */
    @RequestMapping("/contractList")
    public String contractList(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行合同管理列表查询开始...");
        // 构造条件对象
        ContractExample contractExample = new ContractExample();
        // 根据create_time降序排序
        contractExample.setOrderByClause("create_time desc");
        // 获取条件的集合
        ContractExample.Criteria criteria = contractExample.createCriteria();
        // 添加条件
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        /**
         * 合同管理：显示状态为1的购销合同
         */
        criteria.andStateEqualTo(1);
        PageInfo<Contract> pageInfo = contractService.findByPage(contractExample, pageNum, pageSize);
        request.setAttribute("pageInfo", pageInfo);
        return "cargo/export/export-contractList";
    }


    /**
     * 2. 报运单列表
     */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行报运单列表查询开始...");
        // 构造条件对象
        ExportExample exportExample = new ExportExample();
        // 根据create_time降序排序
        exportExample.setOrderByClause("create_time desc");
        // 获取条件的集合
        ExportExample.Criteria criteria = exportExample.createCriteria();
        // 添加条件
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        // 分页查询
        PageInfo<Export> pageInfo = exportService.findByPage(exportExample, pageNum, pageSize);
        request.setAttribute("pageInfo", pageInfo);
        return "cargo/export/export-list";
    }

    /**
     * 3. 合同管理列表，选中购销合同，点击报运，进入报运单添加页面
     * @param id 购销合同的id，多个id自动以逗号隔开
     * @return
     */
    @RequestMapping("/toExport")
    public String toExport(String id){
        request.setAttribute("id",id);
        return "cargo/export/export-toExport";
    }

    /**
     * 4. 报运单添加、修改
     */
    @RequestMapping("/edit")
    public String edit(Export export) {
        // 设置企业id、企业名称
        export.setCompanyId(getLoginCompanyId());
        export.setCompanyName(getLoginCompanyName());
        if (StringUtils.isEmpty(export.getId())) {
            // 设置创建时间
            export.setCreateTime(new Date());
            exportService.save(export);
        } else {
            exportService.update(export);
        }
        return "redirect:/cargo/export/list";
    }

    /**
     * 5. 报运单列表点击修改
     * http://localhost:8080/cargo/export/toUpdate.do?id=0
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id){
        //1. 根据报运单id查询报运单
        Export export = exportService.findById(id);

        //2.根据报运单id查询商品
        ExportProductExample example = new ExportProductExample();
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> exportProducts = exportProductService.findAll(example);

        //3. 保存
        request.setAttribute("export",export);
        request.setAttribute("eps",exportProducts);
        return "cargo/export/export-update";
    }

    /**
     * 报运单状态的修改：提交、取消
     * @param id
     * @return
     */
    @RequestMapping("/submit")
    public String submit(String id) {
        // 提交：报运单状态为1
        Export export = new Export();
        export.setId(id);   // 修改条件
        export.setState(1); // 修改的值
        exportService.update(export);
        return "redirect:/cargo/export/list";
    }

    @RequestMapping("/cancel")
    public String cancel(String id) {
        // 提交：修改报运单状态为0
        Export export = new Export();
        export.setId(id);   // 修改条件
        export.setState(0); // 修改的值
        exportService.update(export);
        return "redirect:/cargo/export/list";
    }

    /**
     * 电子报运实现
     */
    @RequestMapping("/exportE")
    public String exportE(String id){

        // 创建并封装webservice请求参数的ExportVo对象
        ExportVo exportVo = new ExportVo();
        // 根据报运单的id查询
        Export export = exportService.findById(id);
        // 对象拷贝：封装报运单
        BeanUtils.copyProperties(export,exportVo);
        // 【设置报运单的id到vo对象中】
        exportVo.setExportId(id);

        // 封装webservice请求的商品集合
        List<ExportProductVo> products = exportVo.getProducts();

        // 根据报运单id查询商品
        ExportProductExample example = new ExportProductExample();
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> list = exportProductService.findAll(example);
        if (list != null && list.size() > 0){
            for (ExportProduct exportProduct : list) {
                // 创建webservice请求的商品对象
                ExportProductVo vo = new ExportProductVo();
                BeanUtils.copyProperties(exportProduct,vo);
                // 【设置报运单、商品id】
                vo.setExportId(id);
                vo.setExportProductId(exportProduct.getId());
                // 添加到集合
                products.add(vo);
            }
        }

        //1. 电子报运（1）远程访问海关报运平台录入报运单、商品信息
        WebClient.create("http://192.168.85.43:8082/ws/export/user").post(exportVo);

        //2. 电子报运（2）根据报运单id，查询报运结果
        ExportResult exportResult =
                WebClient.create("http://192.168.85.43:8082/ws/export/user/" + id).get(ExportResult.class);

        // 修改数据库：报运单的状态、备注、商品交税金额
        exportService.updateExport(exportResult);
        return "redirect:/cargo/export/list";
    }
}